package com.pizzaonline.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.Element;
import com.pizzaonline.utils.XMLControler;

/**
 * Servlet implementation class for Servlet: SuppressionMenu
 *
 */
 public class SuppressionMenu extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public SuppressionMenu() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//Mode UTF-8
		request.setCharacterEncoding("UTF-8");
		
		//Récupération des paramètres
		String menu = request.getParameter("menu");
		if(menu == null) return;
		PrintWriter out = response.getWriter();
		deleteMenu(out,menu);
	}   	  	  
	
	private void deleteMenu(PrintWriter out,String menu){
		Element temp;
		try{
			XMLControler.readXMLFile("carte.xml");
			System.out.println("Lecture du fichier XML");
			
			Element menus = XMLControler.racine.getChild("Menus");
			List listeMenus = menus.getChildren();
			Iterator iter = listeMenus.iterator();
			while(iter.hasNext()){
				temp = (Element)iter.next();
				if(temp.getAttributeValue("nom").equals(menu)){
					menus.removeContent(temp);
					break;
				}
			}
			XMLControler.saveXMLFile("carte.xml");
			out.println("<b><font color=\"green\">Suppression réussie dans le fichier XML</font></b><br/>");
			out.println("<a href=\"suppression.jsp?mode=menu\">Supprimer un autre menu</a><br/>");
		}
		catch(Exception e){
			System.out.println("Erreur de lecture du fichier XML");
			out.println("<b><font color=\"red\">Erreur de suppression dans le fichier XML</font></b><br/>");
			out.println("<a href=\"suppression.jsp?mode=menu\">Recommencer</a><br/>");	
			e.printStackTrace();
		}
	}
	
	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}   
}